package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //前置.后置.路由.错误处理
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
        //return pre;
    }

    //顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //针对当前这次请求,是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        如果请求商品,执行过滤
        如果请求用户或订单,跳过过滤
         */

        //获取请求上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //获取调用的服务id
        String serviceId=(String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(serviceId);
    }


    //过滤代码,权限判断
    @Override
    public Object run() throws ZuulException {
        //获取request对象
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();

        //接收token参数
        String  token=request.getParameter("token");

        //如果没有token
        if(StringUtils.isBlank(token)){
            // 阻止继续访问
            ctx.setSendZuulResponse(false);

            // 直接返回响应
            // JsonResult {code:200,msg:"xxx",data:null}
            ctx.addZuulResponseHeader("Content-Type", "application/json");
            ctx.setResponseStatusCode(JsonResult.NOT_LOGIN);
            ctx.setResponseBody(JsonResult
                    .err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login").toString());
        }

        return null;//zuul当前版本中,这个返回值没有使用,不发挥任何作用,返回任何数
    }
}
